import React, { PureComponent } from 'react';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col, Select, Input, message } from 'antd';

import TableForm from './TableForm';
import { connect } from 'dva';
import moment from 'moment';
import 'moment/locale/zh-cn';
import { ContentPackage, PrimaryC, TableC, SecondHeaderC, DATA_ENTRY, AdvancedSearch, InputC, SelectC, ModalC, PrimaryGhostC, TenantC } from '../../../comps';

import ModalInst from './Modal';

const { TextArea } = Input;
moment.locale('zh-cn');
const FormItem = Form.Item;
@connect(({ stationModel, userM: user }) => ({
  stationModel,
  user,
}))
@Form.create()
export default class Station extends PureComponent {
  state = {
    titleModal: '新增岗位',
    saveVisible: false,
    formItem: {},
    gwqxSelect: [],
    zhxzSelect: '',
    superMan: localStorage.getItem('antd-pro-superMan'),
    currentPage: 1,
    numInPage: 10,
    isReset: false, //是否点击了重置
    userModalVisible: false, //关联用户模态框显示隐藏
    userSelectData: undefined, //选中的关联用户下拉数据
    userTableData: undefined, //关联用户表格数据
    userSelectDataCompare: undefined, //保存关联用户变更前的数据
    searchObj: {}, //查询条件
  };

  //页面初始函数
  UNSAFE_componentWillMount = () => {
    //查询全部岗位
    this.props.dispatch({
      type: 'stationModel/Search',
      payload: {},
    });

    this.props.dispatch({
      type: 'stationModel/authority',
      payload: {},
    });
    if (localStorage.getItem('antd-pro-superMan') == 'true') {
      this.props.dispatch({
        type: 'stationModel/SearchTenant',
        payload: {},
      });
    }
  };
  // 查询点击
  searchById = (e) => {
    let values = {};
    if (e && JSON.stringify(e) != '{}') {
      values = {
        postName: e.postName.trim(),
      };
    }
    this.setState(
      {
        currentPage: 1,
        isReset: false,
        searchObj: values,
      },
      () => {
        this.props.dispatch({
          type: 'stationModel/save',
          payload: { loading: true },
        });

        this.props.dispatch({
          type: 'stationModel/Search',
          payload: this.state.searchObj,
        });
      },
    );
  };
  // 表格change
  changeReset = (current, pagesize) => {
    const { isReset } = this.state;
    if (isReset) {
      //判断是否点击了重置 点击页码不进行后台查询
      message.warning('查询条件已被重置，请重新查询。');
      this.setState({
        isReset: false,
      });
      return;
    }
    this.setState({
      currentPage: current,
      numInPage: pagesize,
    });
  };
  // 新增
  handleTableSave = () => {
    const { form } = this.props;
    this.props.dispatch({
      type: 'stationModel/SearchUser',
      payload: {},
    });
    form.resetFields(['descriptionModal', 'postTypeCodeModal', 'postTypeModal', 'postCodeModal', 'postNameModal', 'createdBy']);
    this.setState({
      titleModal: '新增岗位',
      saveVisible: true,
      formItem: {},
    });
  };
  // 岗位权限change事件
  handleGLGWChange = (value) => {
    this.setState({
      gwqxSelect: value,
    });
  };
  // 模态框中，关联用户按钮点击事件
  relatedUserClick = () => {
    let tempArr = [];
    this.state.userTableData &&
      this.state.userTableData.forEach((item) => {
        tempArr.push(item.id);
      });

    setTimeout(() => {
      this.props.form.setFieldsValue({
        relatedUser: tempArr,
      });
    }, 0);
    this.setState({
      userSelectDataCompare: tempArr,
      userModalVisible: true,
    });
  };
  // 关联用户模态框内容渲染
  userModal = () => {
    const {
      stationModel: { userData },
    } = this.props;
    return (
      <div>
        <Form>
          <SelectC
            dataIndex='relatedUser'
            form={this.props.form}
            title='关联用户'
            showSearch={true}
            isMultiple={true}
            allowClear={true}
            maxTagCount={0}
            initialValue={this.state.userSelectData || undefined}
            dataSource={userData}
            filterOption={(
              input,
              option, //模糊搜索value 和 title
            ) => {
              return (option && option.props && option.props.children && option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0 )|| (option.props&& option.props.value&&option.props.value.toLowerCase().indexOf(input.toLowerCase()) >= 0)
            }}
            optionTitle={true}
            positionBody={true}
          />
        </Form>
      </div>
    );
  };
  // 关联用户模态框ok事件
  userOk = () => {
    const {
      stationModel: { userOriginData },
    } = this.props;
    let tempSelect = this.props.form.getFieldValue('relatedUser');
    let tempTable = [];
    // 用选中的关联用户select数据遍历处理出关联用户table数据
    if (tempSelect && tempSelect.length > 0) {
      tempSelect &&
        tempSelect.forEach((itemSelect) => {
          userOriginData &&
            userOriginData.forEach((item) => {
              if (item.id == itemSelect) {
                tempTable.push({ id: item.id, name: item.name, userAccount: item.userAccount });
              }
            });
        });
    }
    this.setState({
      userSelectData: tempSelect,
      userTableData: tempTable,
      userModalVisible: false,
    });
  };
  // 关联用户模态框cancel事件
  userCancel = () => {
    this.setState({
      userSelectData: this.state.userSelectDataCompare,
      userModalVisible: false,
    });
  };
  render() {
    const { form } = this.props;
    const { getFieldDecorator } = this.props.form;
    const {
      stationModel: { data, childrenGLGW },
    } = this.props;
    const that = this;
    // 岗位权限
    const getAuthorityData = childrenGLGW.map((item, i) => {
      return <Select.Option key={item.id}>{`${item.name}`}</Select.Option>;
    });
    const table = {
      data,
      // 编辑点击事件
      onEditFrom(item) {
        // 处理关联用户下拉数据
        let tempArr = [];
        item.userModels &&
          item.userModels.map((item) => {
            tempArr.push(item.id);
          });

        that.props.dispatch({
          type: 'stationModel/SearchUser',
          payload: {},
        });
        that.setState({
          userSelectData: tempArr,
          userTableData: item.userModels || undefined,
        });
        form.resetFields(['descriptionModal', 'postTypeCodeModal', 'postTypeModal', 'postCodeModal', 'postNameModal', 'createdBy']);
        let gwqxSelect2 = item.newKey.split(' ');
        if (gwqxSelect2[gwqxSelect2.length - 1] == '' || gwqxSelect2 == ['']) {
          gwqxSelect2.pop();
        }

        that.setState({
          titleModal: '修改岗位',
          saveVisible: true,
          formItem: item,
          gwqxSelect: gwqxSelect2,
        });
      },
      onDeleteFrom: (item) => {
        this.props.dispatch({
          type: 'stationModel/deleteById',
          payload: item.id,
          callback: (res) => {
            if (res == 'success') {
              //查询全部岗位
              this.props.dispatch({
                type: 'stationModel/Search',
                payload: that.state.searchObj,
              });
            }
          },
        });
      },
    };

    const modal = {
      titleModal: that.state.titleModal,
      saveVisible: that.state.saveVisible,
      // 新增编辑模态框的内容渲染
      saveModal() {
        return (
          <Form>
            <Row>
              <Col span={12} style={{ marginBottom: '10px' }}>
                <InputC
                  form={that.props.form} // form对象
                  dataIndex={'postNameModal'}
                  title={'岗位名称'}
                  formItemLayout={formItemLayout}
                  initialValue={that.state.formItem.postName}
                  rules={[{ required: true, max: 100, message: '请输入岗位名称' }]}
                />
              </Col>
              <Col span={12} style={{ marginBottom: '10px' }}>
                <InputC
                  form={that.props.form} // form对象
                  dataIndex={'postCodeModal'}
                  title={'岗位代码'}
                  formItemLayout={formItemLayout}
                  initialValue={that.state.formItem.postCode}
                  disabled={that.state.titleModal == '修改岗位' ? true : false}
                  rules={[{ required: true, max: 100, message: '请输入岗位名称' }]}
                />
              </Col>
            </Row>
            <Row>
              <Col span={12} style={{ marginBottom: '10px' }}>
                {that.state.superMan == 'true' ? (
                  <TenantC
                    title='租户选择'
                    form={that.props.form}
                    dataIndex='createdBy'
                    disabled={that.state.titleModal == '修改岗位' ? true : false}
                    initialValue={that.state.formItem.createdBy}
                    showSearch={true}
                    formItemLayout={formItemLayout}
                    optionTitle={true}
                  />
                ) : null}
              </Col>
              {/* <Col span={12} style={{ marginBottom: '10px' }}>
                <FormItem
                  label="岗位权限"
                  {...formItemLayout}
                >
                  <Select
                    mode="multiple"
                    allowClear
                    style={{ width: '100%' }}
                    placeholder="请选择岗位权限"
                    value={that.state.gwqxSelect}
                    onChange={that.handleGLGWChange}
                  >
                    {getAuthorityData}
                  </Select>
                </FormItem>
              </Col> */}
            </Row>
            <Row>
              <Col span={24} style={{ marginBottom: '10px' }}>
                <FormItem label='描述' {...formItemLayout2}>
                  {getFieldDecorator('descriptionModal', { initialValue: that.state.formItem.description })(<TextArea placeholder='请输入' maxLength='32' rows={1} />)}
                </FormItem>
              </Col>
            </Row>
          </Form>
        );
      },
      // 关联用户信息
      relatedUser() {
        const userColumns = [
          {
            title: '用户名称',
            dataIndex: 'name',
            key: 'name',
          },
          {
            title: '用户账号',
            dataIndex: 'userAccount',
            key: 'userAccount',
          },
        ];
        return (
          <div style={{ width: '100%' }}>
            <SecondHeaderC title='关联用户信息' Right={<PrimaryGhostC title='关联用户' onClick={that.relatedUserClick} />} />
            <div style={{ marginTop: '10px' }}>
              <TableC columns={userColumns} scroll={{ y: 180 }} hidePage={true} rowKey={'id'} dataSource={that.state.userTableData} />
            </div>
          </div>
        );
      },
      // 模态框确认点击事件
      confirmRevise(e) {
        e.preventDefault();
        const {
          user: { currentUser },
        } = that.props;
        const { userSelectData } = that.state;
        const { form } = that.props;
        // 关联用户数据处理后传给后端
        let tempUserData = [];
        userSelectData &&
          userSelectData.map((item) => {
            tempUserData.push({ id: item });
          });

        form.validateFields(['descriptionModal', 'postTypeCodeModal', 'postTypeModal', 'postCodeModal', 'postNameModal', 'createdBy'], (err, fieldsValue) => {
          if (err) return;
          const postAuthority = [];
          that.state.gwqxSelect.map((item, i) => {
            return postAuthority.push({ id: item });
          });
          if (that.state.titleModal == '新增岗位') {
            // 新增
            const values = {
              postName: fieldsValue.postNameModal,
              postCode: fieldsValue.postCodeModal,
              postType: fieldsValue.postTypeModal,
              postTypeCode: fieldsValue.postTypeCodeModal,
              createdBy: fieldsValue.createdBy,
              description: fieldsValue.descriptionModal,
              stationAuthorities: postAuthority,
              userModels: tempUserData, //关联用户
            };
            that.props.dispatch({
              type: 'stationModel/save',
              payload: { loading: true },
            });
            that.props.dispatch({
              type: 'stationModel/saveTable',
              payload: values,
              callback: (type) => {
                if (type == 'success') {
                  // 清空
                  that.setState({
                    saveVisible: false,
                    gwqxSelect: [],
                    userSelectData: [],
                    userTableData: [],
                  });
                  that.props.dispatch({
                    type: 'stationModel/Search',
                    payload: that.state.searchObj,
                  });
                }
              },
            });
          } else {
            // 编辑
            const values = {
              id: that.state.formItem.id,
              postName: fieldsValue.postNameModal,
              postCode: fieldsValue.postCodeModal,
              postType: fieldsValue.postTypeModal,
              postTypeCode: fieldsValue.postTypeCodeModal,
              description: fieldsValue.descriptionModal,
              createdBy: that.state.formItem.createdBy,
              createdTs: that.state.formItem.createdTs,
              lastUpdBy: currentUser.name,
              stationAuthorities: postAuthority,
              userModels: tempUserData, //关联用户
            };
            that.props.dispatch({
              type: 'stationModel/save',
              payload: { loading: true },
            });
            that.props.dispatch({
              type: 'stationModel/saveTable',
              payload: values,
              callback: (type) => {
                if (type == 'success') {
                  // 清空
                  that.setState({
                    saveVisible: false,
                    gwqxSelect: [],
                    userSelectData: [],
                    userTableData: [],
                  });
                  that.props.dispatch({
                    type: 'stationModel/Search',
                    payload: that.state.searchObj,
                  });
                }
              },
            });
          }
        });
      },
      // 模态框取消点击事件
      cancel() {
        that.setState({
          saveVisible: false,
          gwqxSelect: [],
          userSelectData: [],
          userTableData: [],
        });
      },
    };
    const formItemLayout = {
      labelCol: {
        xs: { span: 5, offset: 0 },
        sm: { span: 8, offset: 0 },
        md: { span: 8, offset: 0 },
        lg: { span: 8, offset: 0 },
        xl: { span: 8, offset: 0 },
        xxl: { span: 8, offset: 0 },
      },
      wrapperCol: {
        xs: { span: 17, offset: 0 },
        sm: { span: 16, offset: 0 },
        md: { span: 16, offset: 0 },
        lg: { span: 16, offset: 0 },
        xl: { span: 16, offset: 0 },
        xxl: { span: 16, offset: 0 },
      },
    };
    const formItemLayout2 = {
      labelCol: {
        xs: { span: 1, offset: 0 },
        sm: { span: 4, offset: 0 },
        md: { span: 4, offset: 0 },
        lg: { span: 4, offset: 0 },
        xl: { span: 4, offset: 0 },
        xxl: { span: 4, offset: 0 },
      },
      wrapperCol: {
        xs: { span: 21, offset: 0 },
        sm: { span: 20, offset: 0 },
        md: { span: 20, offset: 0 },
        lg: { span: 20, offset: 0 },
        xl: { span: 20, offset: 0 },
        xxl: { span: 20, offset: 0 },
      },
    };
    const searchProps = {
      dataSource: [
        {
          dataIndex: 'postName',
          title: '岗位名称/代码',
          type: DATA_ENTRY.INPUT,
          allowClear: true,
        },
      ],
      //点击查询按钮
      onQuery: (e) => {
        this.searchById(e);
      },
      onClear: () => {
        //点击重置按钮
        this.setState({
          isReset: true,
          searchObj: {},
        });
      },
    };
    return (
      <ContentPackage
        title='岗位配置'
        contentHtml={
          <div>
            <div>
              <AdvancedSearch {...searchProps} />
              <PrimaryC title='新增' style={{ margin: '10px' }} onClick={this.handleTableSave} />
            </div>
            <TableForm {...table} changeReset={this.changeReset} currentPage={this.state.currentPage} numInPage={this.state.numInPage} />
            <ModalInst {...modal} />
            <ModalC title={'关联用户'} visible={this.state.userModalVisible} onOk={this.userOk} onCancel={this.userCancel} width={450}>
              {this.userModal()}
            </ModalC>
          </div>
        }
      />
    );
  }
}
